package cn.jekun.shop.common.service;

import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Email;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsMessageHis;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsMessageHisService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.validator.annotation.UserName;
import cn.jekun.shop.web.bean.UserStat;

/**
 * 
 * @author twj
 *
 */
@Service(UserService.BEAN_NAME)
public class UserService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.UserService";
	@Override
	public String getNamespace() {
		return "SHOP_USER";
	}
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	@Resource(name = ErpOrdersService.BEAN_NAME)
	private ErpOrdersService erpOrdersService;
	@Resource(name = McMemberService.BEAN_NAME)
	private McMemberService mcMemberService;
	@Resource(name = RsMessageHisService.BEAN_NAME)
	private RsMessageHisService rsMessageHisService;
	/**
	 * 获取个人的统计信息(
	 * 		积分：5620 
			待收货订单：1份 
			待付款订单：2份 
			已成功订单：
	 * @param userId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getStatInfo(
			@Security
			String userId) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put("userId", userId);
			UserStat userOrderStat = this.one(this.getStatementName("userOrderStat"), map);
			UserStat userCreditsStat = this.one(this.getStatementName("userCreditsStat"), map);
			if (userOrderStat == null) {
				userOrderStat = new UserStat();
			}
			if (userCreditsStat!=null) {
				userOrderStat.setUserName(userCreditsStat.getUserName());
				userOrderStat.setCreditsTotal(userCreditsStat.getCreditsTotal());
			}
			return this.executeRerutn(JSONObject.fromObject(userOrderStat));
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 获取用户信息
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getUserInfo(
			@Security
			String userId){
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码为空");
		}
		Map userMap = new HashMap();
		userMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(userMap,
				SqlUtis.getSQL(userMap, "a."+ RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
		RsUser rsUser = this.rsUserService.one(userMap);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		if(rsUser == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户信息不存在");
		}
		rsUser.setPassword("");
		String tempIconUrl = rsUser.getIconUrl();
		rsUser.setIconUrl(tempIconUrl);
		JSONObject json =  JSONObject.fromObject(rsUser, jsonConfig);
		jsonObject.put("RsUser", json);
		//订单总数
		Map orderCountMap = new HashMap();
		orderCountMap.put(RsUser.COL_USER_ID, userId);
		orderCountMap.put(ErpOrders.COL_ORDER_STATUS_ID, 
				Constants.ERP_ORDER_STATUS.MEDIATE
				+","+Constants.ERP_ORDER_STATUS.ORDER
				+","+Constants.ERP_ORDER_STATUS.PAY
				+","+Constants.ERP_ORDER_STATUS.REJECT_RECEIPT
				+","+Constants.ERP_ORDER_STATUS.SHIPPING
				);
		SqlUtis.prepareSql(orderCountMap,
				SqlUtis.getSQL(orderCountMap, "a."+ RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(orderCountMap, "a."+ ErpOrders.COL_ORDER_STATUS_ID)
				);
		int orderCount = this.erpOrdersService.count(orderCountMap);
		//我的收藏
		Map hashMap = new HashMap();
		hashMap.put(RsUser.COL_USER_ID, userId);
		hashMap.put(McMember.COL_CONCERN, "1");
		SqlUtis.prepareSql(hashMap,
				SqlUtis.getSQL(hashMap, "a."+ RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(hashMap, "a."+ McMember.COL_CONCERN,Types.VARCHAR,SqlUtis.EQ)
				);
		int memberCount = this.mcMemberService.count(hashMap);
		Map noticeMap = new HashMap();
		noticeMap.put(RsMessageHis.COL_CLIENT_ID, "u_"+userId);
		noticeMap.put(RsMessageHis.COL_READED, "0");
		noticeMap.put(RsMessageHis.COL_STATUS, "2");
		//通知数
		SqlUtis.prepareSql(noticeMap,
				SqlUtis.getSQL(noticeMap, "a."+ RsMessageHis.COL_CLIENT_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(noticeMap, "a."+ RsMessageHis.COL_READED,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(noticeMap, "a."+ RsMessageHis.COL_STATUS,Types.VARCHAR,SqlUtis.EQ));
		int noticeCount = this.rsMessageHisService.count(noticeMap);
		jsonObject.put("orderCount",orderCount);
		jsonObject.put("memberCount",memberCount);
		jsonObject.put("noticeCount",noticeCount);
		return executeRerutn(jsonObject);
	}
	/**
	 * 更新用户信息
	 * @param userId
	 * @param userName
	 * @param mobile
	 * @param sex
	 * @param birthday
	 * @param phone
	 * @param email
	 * @param address
	 * @param zipCode
	 * @param myFile
	 * @param myFileFileName
	 * @param myFileContentType
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	@Transactional
	public JSONObject updateUserInfo(
			@RsUser.AnnoUserId
			String userId, 
			@UserName
			String userName,
			@Mobile(message="手机号非法")
			String mobile, 
			@RsUser.AnnoSex
			String sex, 
			@RsUser.AnnoBirthday
			String birthday, 
			@RsUser.AnnoPhoneNumber
			String phone,
			@Email(message="邮箱格式非法")
			@RsUser.AnnoEmail
			String email, 
			@RsUser.AnnoAddress
			String address,
			@RsUser.AnnoZipcode
			String zipCode,
			@RsUser.AnnoRealName
			String realName,
			@RsUser.AnnoIconUrl
			String iconUrl,
			@Security
			String nickName) throws Exception {
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		RsUser rsUser = new RsUser();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码为空");
		}
		if (StringUtils.isBlank(userName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户名为空");
		}
		if (StringUtils.isBlank(birthday)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"生日不能为空");
		}
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号为空");
		}
		if (StringUtils.isBlank(email)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"邮箱不能为空");
		}
		if(StringUtils.isNotBlank(birthday)){
			  DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
			  Date userBirthday = fmt.parse(birthday);
			  rsUser.setBirthday(userBirthday);
		}
		Map tempUserMap = new HashMap();
		tempUserMap.put(RsUser.COL_USER_ID, userId);
		tempUserMap.put(RsUser.COL_USER_NAME, userName);
		tempUserMap.put(RsUser.COL_MOBILE, mobile);
		SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		RsUser tempUser = new RsUser();
		tempUser = this.rsUserService.one(tempUserMap);
		
		if(tempUser != null){
			//如果用户名变则验证
			if(!tempUser.getUserName().equals(userName)){
				SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_USER_NAME, Types.VARCHAR,SqlUtis.EQ));
				if(this.rsUserService.exists(tempUserMap)){
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"用户名已存在");
				}
			}
			//如果手机有变则验证
			else if(!tempUser.getMobile().equals(mobile)){
				SqlUtis.prepareSql(tempUserMap,"",SqlUtis.getSQL(tempUserMap, "a."+ RsUser.COL_MOBILE, Types.VARCHAR,SqlUtis.EQ));
				if(this.rsUserService.exists(tempUserMap)){
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"手机号已存在");
				}
				
			}
			rsUser.setMobile(mobile);
			rsUser.setUserName(userName);
			
		}
		rsUser.setAddress(address);
		rsUser.setRealName(realName);
		rsUser.setEmail(email);
		rsUser.setSex(sex);
		rsUser.setZipcode(zipCode);
		rsUser.setPhoneNumber(phone);
		rsUser.setIconUrl(iconUrl);
		formMap.put(RsUser.COL_USER_ID, userId);
		formMap.put("rsUser", rsUser);
		SqlUtis.prepareSql(formMap,"",SqlUtis.getSQL(formMap, "a."+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		int count = this.rsUserService.update(formMap);
		if(count != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
	/**
	 * app修改用户资料
	 * @return
	 * @throws ParseException 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject appUpdateUserInfo(
			@RsUser.AnnoUserId
			String userId,
			@RsUser.AnnoPhoneNumber
			String phoneNumber,
			@RsUser.AnnoSex
			String sex,
			@RsUser.AnnoBirthday
			String birthday,
			@Security
			String nickName,
			@RsUser.AnnoAddress
			String address,
			@RsUser.AnnoIconUrl
			String userIconUrl,
			@RsUser.AnnoRealName
			String realName) throws ParseException{
		JSONObject jsonObject = new JSONObject();
		RsUser rsUser = new RsUser();
		
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		/*if (StringUtils.isBlank(birthday)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"生日不能为空");
		}*/
		if(StringUtils.isNotBlank(birthday)){
			  DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
			  Date userBirthday = fmt.parse(birthday);
			  rsUser.setBirthday(userBirthday);
		}
		if(StringUtils.isNotBlank(userIconUrl)){
			  rsUser.setIconUrl(userIconUrl);
		}
		if(StringUtils.isNotBlank(address)){
			  rsUser.setAddress(address);
		}
		if(StringUtils.isNotBlank(phoneNumber)){
			  rsUser.setPhoneNumber(phoneNumber);
		}
		if(StringUtils.isNotBlank(nickName)){
			 // rsUser.setNickName(nickName);
		}
		if(StringUtils.isNotBlank(realName)){
			  rsUser.setRealName(realName);
		}
		rsUser.setSex(sex);
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap,"",SqlUtis.getSQL(formMap, "a."+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		boolean flag = this.rsUserService.exists(formMap);
		if(!flag){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		formMap.put("rsUser", rsUser);
		int count = this.rsUserService.update(formMap);
		if(count != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

}
